package com.tgy.JUC.producerConsumer;

/***
 * @ClassName: PCSynchronized
 * @Description: 生产者消费者，Synchronized版本
 * @Auther: 送你一块二向箔
 * @Date: 9:39 2022/3/11
 * @version : V1.0
 */
public class PCSynchronized {
    public static void main(String[] args) {
        Data data = new Data();
        new Thread(()->{for (int i = 0; i < 10; i++) data.increment();},"A").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.decrement();},"B").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.increment();},"C").start();
        new Thread(()->{for (int i = 0; i < 10; i++) data.decrement();},"D").start();

    }


}

// 判断等待，业务，通知
class Data {
    private int i = 0;

    // +1
    public synchronized void increment()  {
        while (i != 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        i++;
        System.out.println(Thread.currentThread().getName() + "=>" + i);
        // 通知其他线程我+1完成
        this.notifyAll();
    }

    // -1
    public synchronized void decrement()  {
        while (i == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        i--;
        System.out.println(Thread.currentThread().getName() + "=>" + i);
        // 通知其他线程，我-1完毕
        this.notifyAll();
    }
}
